package com.cictec.middleware.tde.rm;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Properties;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PrettyMemoryUtils;

public class MinaClient extends IoHandlerAdapter {

	private String resource = "test.properties";
	private IoConnector connector;
	private IoSession session;
	private boolean isConnectClose = false;

	private static Properties prop = null;

	private String clientId = null;
	
	public MinaClient(String clientId) {
		this.clientId = clientId;
		this.connector = new NioSocketConnector();
		this.connector.setHandler(this);
		prop = getProperties();

		String ip = prop.getProperty("clientIp");
		int port = 9652;
		if(ip == null){
			ip = "0.0.0.0";
		}

		String portStr = prop.getProperty("clientport");
		if (portStr != null) {
			port = Integer.parseInt(portStr);
		}

		ConnectFuture connFuture = this.connector.connect(new InetSocketAddress(ip, port));
		connFuture.awaitUninterruptibly();
		session = connFuture.getSession();
		System.out.println("TCP 客户端启动");
	}

	
	public void send(List<String> lists) throws Exception {

		String loadDataCycle = prop.getProperty("loadDataCycle");
		long dataCycle = 6000L;
		if (!PMSUtils.isEmpty(dataCycle)) {
			dataCycle = Long.parseLong(loadDataCycle);
		}

		long size = 0;
		for (int j = 0; j < lists.size(); j++) {
			
			if(isConnectClose){
				break;
			}
			
			byte[] bts = new byte[20];
			for (int i = 0; i < 20; i++) {
				bts[i] = (byte) i;
			}
			IoBuffer buffer = IoBuffer.allocate(10);

			buffer.setAutoExpand(true);

			buffer.setAutoShrink(true);

			bts = HexString2Bytes(((String) lists.get(j)).replaceAll(" ", ""));
			buffer.put(bts);
			buffer.flip();
			
			size += bts.length;
			session.write(buffer);

			System.out.println("客户端-" + clientId +"\t推送第 " + j + " 条，共 " + lists.size() + " 条记录");
			Thread.sleep(dataCycle);
		}
		System.out.println("长度"+PrettyMemoryUtils.prettyByteSize(size));

		connector.dispose(true);
		System.out.println("数据发送完毕！");
	}

	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) (parse(c0) << 4 | parse(c1));
		}
		return b;
	}

	private static int parse(char c) {
		if (c >= 'a')
			return c - 'a' + 10 & 0xF;
		if (c >= 'A')
			return c - 'A' + 10 & 0xF;
		return c - '0' & 0xF;
	}

	public static String str2HexStr(String str) {
		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();

		for (int i = 0; i < bs.length; i++) {
			int bit = (bs[i] & 0xF0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0xF;
			sb.append(chars[bit]);
			sb.append(' ');
		}
		return sb.toString().trim();
	}

	public void messageReceived(IoSession iosession, Object message) throws Exception {
		IoBuffer bbuf = (IoBuffer) message;
		byte[] byten = new byte[bbuf.limit()];
		bbuf.get(byten, bbuf.position(), bbuf.limit());
	}

	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		System.out.println("客户端异常");
		isConnectClose = true;
		super.exceptionCaught(session, cause);
	}

	public void messageSent(IoSession iosession, Object obj) throws Exception {
		super.messageSent(iosession, obj);
	}

	public void sessionClosed(IoSession iosession) throws Exception {
		System.out.println("客户端会话关闭");
		isConnectClose = true;
		super.sessionClosed(iosession);
	}

	public void sessionCreated(IoSession iosession) throws Exception {
		System.out.println("客户端会话创建");
		super.sessionCreated(iosession);
	}

	public void sessionIdle(IoSession iosession, IdleStatus idlestatus) throws Exception {
		System.out.println("客户端会话休眠");
		super.sessionIdle(iosession, idlestatus);
	}

	public void sessionOpened(IoSession iosession) throws Exception {
		System.out.println("客户端会话打开");
		super.sessionOpened(iosession);
	}
	
	public Properties getProperties() {
		if (prop == null) {
			prop = new Properties();
			InputStream is = MinaTcpClientMutil.class.getClassLoader().getResourceAsStream(resource);
			try {
				prop.load(is);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		return prop;
	}
}
